import numpy as np
import cv2
import math

# 判断鼠标是否按下
drawing = False
# 切换图样模式
mode = True
# 当前坐标
ix, iy = -1, -1


def draw_by_mouse(event, x, y, flags, param):
    global ix, iy, drawing, mode
    if event == cv2.EVENT_LBUTTONDOWN:
        drawing = True
        ix, iy = x, y

    if event == cv2.EVENT_MOUSEMOVE and flags == cv2.EVENT_FLAG_LBUTTON:
        if drawing:

            if mode:
                cv2.rectangle(img, (ix, iy), (x, y), (0, 255, 0), -1, 8, 0)
            else:
                radius = int(np.sqrt(abs(x - ix) ** 2 + abs(y - iy) ** 2))
                cv2.circle(img, (ix, iy), radius, (255, 0, 0), -1)

    if event == cv2.EVENT_LBUTTONUP:
        drawing = False


# 创建图像与窗口并将窗口与回调函数绑定
img = np.zeros((500, 500, 3), np.uint8)
cv2.namedWindow('image')
cv2.setMouseCallback('image', draw_by_mouse)

while (1):
    cv2.imshow('image', img)
    k = cv2.waitKey(1) & 0xFF
    if k == ord('q'):  # 按q键退出
        break
    if k == ord('m'):  # 按m切换模式
        mode = not mode

cv2.destroyAllWindows()
